package com.itheima.filter;

/*
    字符集编码统一过滤器处理类
    处理post中文乱码处理

    1.实现Filter接口  重写doFilter   javax.servlet
    2.
 */

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//注解配置过滤器
//@WebFilter(value = "/*",initParams = {@WebServlet(name = "encoding",value = "UTF-8")})

public class EncodingFilter implements Filter {
    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding=filterConfig.getInitParameter("encoding");
    }

    //实现过滤的方法
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将servletRequest, servletResponse 转换成Http
        //类型转换  需向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //设置字符集  处理中文乱码
        request.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);

        //调用过滤器链上的下一个过滤器,如果没有过滤器了,就执行请求资源
        //过滤器链  filterChain.doFilter(request,response)
        //request,response  传给下一个过滤器
        filterChain.doFilter(request,response);
    }
}

